package com.yn.module.spider.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yn.module.spider.config.strategy.SpiderConfig;
import com.yn.module.spider.mapper.NatmcMedicareMaterialDetailMapper;
import com.yn.module.spider.pojo.NatmcMedicareMaterial;
import com.yn.module.spider.pojo.NatmcMedicareMaterialDetail;
import com.yn.module.spider.utils.base.DefaultDetailSpiderService;
import com.yn.module.spider.utils.constant.OptEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

@Service
@SpiderConfig(type = OptEnum.OpearionType_Detail, svc = OptEnum.SpiderOpertion_NationMedicare_MedicareMaterialDetail)
@Slf4j
@Transactional
public class NatmcMedicareMaterialDetailService extends DefaultDetailSpiderService<NatmcMedicareMaterialDetailMapper, NatmcMedicareMaterialDetail> {

    @Resource
    private NatmcMedicareMaterialService mainTableService;

    @Override
    public void saveData2Db(String json, Map<String, Object> selfParams) throws Exception {
        JSONObject jsonObject = JSON.parseObject(json);
        Object rows = jsonObject.get("rows");
        Long pid = (Long) selfParams.get("pid");
        Integer totalRecords = (Integer) jsonObject.get("records");

        if (rows != null) {
            List<NatmcMedicareMaterialDetail> dataList = JSON.parseArray(rows.toString(), NatmcMedicareMaterialDetail.class, JSONReader.Feature.FieldBased);
            if (totalRecords >= 100) {
                log.info("数据不全，第一条数据为--》", dataList.get(0));
                throw new RuntimeException("明细：：数据不全");
            }
            Optional.ofNullable(dataList).orElse(new ArrayList<>()).stream().forEach(obj -> {
                obj.setEid(IdWorker.getId());
                obj.setPid(pid);
                obj.setSysId(obj.getId());
                obj.setTs(new Date());
                obj.setPage((Integer) selfParams.get("page"));
                obj.setLine((Integer) selfParams.get("line"));
                obj.setDataVer((String) selfParams.get(DATA_VERSION));
            });
            saveBatch(dataList);
        }
    }


    @Override
    public List<?> queryParentDataList(int length, Long startPid, String dataVersion) {
        LambdaQueryWrapper<NatmcMedicareMaterial> mainQueryWrapper = new LambdaQueryWrapper<>();
        mainQueryWrapper.ge(NatmcMedicareMaterial::getEid, startPid)
                .eq(NatmcMedicareMaterial::getDataVer, dataVersion);
        mainQueryWrapper.last(" limit " + length);
        List<NatmcMedicareMaterial> dataList = mainTableService.list(mainQueryWrapper);
        return dataList;
    }

    @Override
    public Long queryMaxPid(String dataVersion) {
        LambdaQueryWrapper<NatmcMedicareMaterialDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NatmcMedicareMaterialDetail::getDataVer, dataVersion).orderByDesc(NatmcMedicareMaterialDetail::getPid).last(" limit 1 ");
        List<NatmcMedicareMaterialDetail> dataList = this.list(queryWrapper);
        if (ObjectUtils.isEmpty(dataList)) {
            return 0L;
        }
        return dataList.get(0).getPid();
    }


    @Override
    public Long queryMaxMainTableId(String dataVersion) {
        LambdaQueryWrapper<NatmcMedicareMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NatmcMedicareMaterial::getDataVer, dataVersion).orderByDesc(NatmcMedicareMaterial::getEid).last(" limit 1 ");
        List<NatmcMedicareMaterial> dataList = mainTableService.list(queryWrapper);
        if (ObjectUtils.isEmpty(dataList)) {
            return -1000L;
        }
        return dataList.get(0).getEid();
    }

    @Override
    public void setParams(Object mainObj, Map<String, Object> httpParams, Map<String, Object> selfParams) {
        NatmcMedicareMaterial obj = (NatmcMedicareMaterial) mainObj;
        httpParams.put("releaseVersion", obj.getDataVer());
        httpParams.put("rows", 200);
        httpParams.put("page", 1);
        httpParams.put("sord", "asc");
        httpParams.put("specificationCode", obj.getSpecificationCode()); // 父级的医用耗材编码
        selfParams.put("pid", obj.getEid());
        selfParams.put("page", obj.getPage());
        selfParams.put("line", obj.getLine());
        selfParams.put(DATA_VERSION, obj.getDataVer());
    }
}

